package com.sylar.happyreader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

import com.sylar.happyreader.bean.BookItem;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.net.NetInfo;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.tools.Utils;

public class LoadingActivity extends Activity {
	private final int blockTime = 200;
	private int changeTime = 2000;
	private int changeLoop = 1;
	private boolean canLogin = true;
	boolean exit = false;
	private Context context;
	private int appVcode = -1;
	private int serviceVcode = -1;
	private String style;

	private List<BookItem> books = new ArrayList<BookItem>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		context = this.getBaseContext();
		
		Display display = getWindowManager().getDefaultDisplay();
		Config.screenWidth = display.getWidth();
		Config.screenHeight = display.getHeight();
		
//		loadingCanvas = new LoadingCanvas(this);
		
		ImageView img = new ImageView(getApplicationContext());
		img.setScaleType(ScaleType.FIT_XY);
		img.setImageResource(R.drawable.logo);
		
		setContentView(img);
		
		if (!NetInfo.isNetworkAvailable(context)) {
			LoadingActivity.this.myMessageHandler.sendMessage(myMessageHandler.obtainMessage(300));
		} else {
			new Thread() {
				public void run() {
//					getVersion();
					Message m = new Message();
					if (serviceVcode > appVcode) {
						m.what = 350;
					}else{
						getLogin();
						if (!canLogin) {
							m.what = 250;
						} else {
							m.what = 200;
						}
					}
					myMessageHandler.sendMessage(m);
				}
			}.start();
		}

	}
		

	Handler myMessageHandler = new Handler() {
		public void handleMessage(Message msg) {
			Intent intent = null;
			switch (msg.what) {
			case 200:
				intent = new Intent();
				intent.setClass(LoadingActivity.this, MainTabActivity.class);
				intent.putExtra("books", (Serializable)books);
				startActivity(intent);
				finish();
				break;
			case 250:
				intent = new Intent();
				intent.setClass(LoadingActivity.this, BookListActivity.class);
				startActivity(intent);
				Toast.makeText(context, "亲爱的用户，你的网络不给力呀，请一会再试试..", Toast.LENGTH_LONG).show();
				finish();
				
				break;
			case 300:
				intent = new Intent();
				intent.setClass(LoadingActivity.this, BookListActivity.class);
				startActivity(intent);
				Toast.makeText(context, "亲爱的用户，您还没联网呀！", Toast.LENGTH_LONG).show();
				finish();
				break;
			case 350:
				new AlertDialog.Builder(LoadingActivity.this).setTitle("提示").setMessage("亲爱的用户，你当前使用的版本过低，已不被支持，请下载最新版本哦^_^")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(Config.RequestUri+"/yixs.apk"));
						startActivity(it);
						finish();
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						android.os.Process.killProcess(android.os.Process.myPid());
						System.exit(0);
					}
				}).show();
				break;
			}
			super.handleMessage(msg);
		}

	};

	protected void getLogin() {
		try {

			BookApplication myApp = (BookApplication) getApplication();
			try {
				myApp.setmCurPageBitmap(Bitmap.createBitmap(Config.screenWidth, Config.screenHeight, Bitmap.Config.RGB_565));
				myApp.setmNextPageBitmap(Bitmap.createBitmap(Config.screenWidth, Config.screenHeight, Bitmap.Config.RGB_565));
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
			
//			getServiceCofig();
			
			style = Config.styleList[getRandom(0, 7)];
			
			String contentUrl = Config.RequestUri + "sex=man&style=" + Uri.encode(style);
			String manbooklists = HttpTool.getString(getApplicationContext(), contentUrl);
			
			if(!TextUtils.isEmpty(manbooklists)){
				books.clear();
				String[] manbooklist = manbooklists.split(":");
				manbooklist = Utils.SubArray(manbooklist);
				for(String item:manbooklist){
					BookItem book = new BookItem(item,"man",style);
					books.add(book);
				}
			}
			
		} catch (Exception e) {
			canLogin = false;
			e.printStackTrace();
		}
	}
	

//		protected void getVersion() {
//			String serviceVersion = MobclickAgent.getConfigParams(LoadingActivity.this, "appversion");
//			BookApplication myApp = (BookApplication) getApplication();
//			appVcode = myApp.getVersionCode();
//			if(serviceVersion!=null && !"".equals(serviceVersion))
//			serviceVcode = Integer.valueOf(serviceVersion);
//			
//		}
		
//		protected void getServiceCofig(){
//			String adid = MobclickAgent.getConfigParams(LoadingActivity.this, "adid");
//			String adShowDelay = MobclickAgent.getConfigParams(LoadingActivity.this, "adshowdelay");
//			String adShowTime = MobclickAgent.getConfigParams(LoadingActivity.this, "adshowtime");
//			String yuming = MobclickAgent.getConfigParams(LoadingActivity.this, "yuming");
//			String mobile = MobclickAgent.getConfigParams(LoadingActivity.this, "2g");
//			String adclick = MobclickAgent.getConfigParams(LoadingActivity.this, "adclick");
//			String sharebook = MobclickAgent.getConfigParams(LoadingActivity.this, "sharebook");
//			try {
//				if(adclick!=null && !"".equals(adclick))
//					Config.adClickLife = Integer.valueOf(adclick);
//			} catch (Exception e) {
//				Config.adClickLife = 10;
//			}
//			
//			if(sharebook!=null && !"".equals(sharebook)){
//				Config.shareMsg = sharebook;
//			}
//			
//			if(adid!=null && !"".equals(adid))
//				Config.adid = adid;
//			
//			if(adShowDelay!=null && !"".equals(adShowDelay))
//				Config.adshowdelay = Integer.valueOf(adShowDelay);
//			
//			if(adShowTime!=null && !"".equals(adShowTime))
//				Config.adShowTime = Integer.valueOf(adShowTime);
//			
//			int netType = net.getNetState(LoadingActivity.this);
//			if(mobile !=null && !"".equals(mobile) && netType == 2){
//				Config.RequestUri = mobile + "/tom/servlet/read?";
//				Config.RequestPkgUri  = mobile + "/tom/servlet/total?cmd=update";
//				Config.teamHomeUrl = mobile;
//				Config.teamAboutUrl = mobile+"/sjzqbabout.html";
//			}else{
//				if(yuming!=null && !"".equals(yuming)){
//					Config.RequestUri = yuming + "/tom/servlet/read?";
//				}
//			}
//		}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(1);
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	public static int getRandom(int start, int end) {
		if (start > end || start < 0 || end < 0) {
			return -1;
		}
		return (int) (Math.random() * (end - start + 1)) + start;
	}
}
